/**
 * Socket连接身份验证测试脚本
 * 用于验证修复后的Cookie解析和用户身份验证功能
 */

const io = require('socket.io-client');

async function testSocketAuth() {
  console.log('🧪 开始测试Socket身份验证功能...\n');

  // 测试用例1: 无Cookie连接
  console.log('📝 测试1: 无Cookie连接（应该显示未认证用户）');
  const socket1 = io('http://localhost:7002', {
    transports: ['websocket'],
    withCredentials: false,
    forceNew: true,
    autoConnect: false
  });

  socket1.on('connect', () => {
    console.log('✅ Socket1连接成功');
    socket1.emit('joinRoom', { roomName: 'test-room-1' });
  });

  socket1.on('permission', (data) => {
    console.log('🔐 Socket1权限信息:', data);
    socket1.disconnect();
  });

  socket1.on('connect_error', (error) => {
    console.log('❌ Socket1连接错误:', error.message);
  });

  socket1.connect();

  // 等待测试1完成
  await new Promise(resolve => setTimeout(resolve, 2000));

  // 测试用例2: 携带有效Cookie连接
  console.log('\n📝 测试2: 携带Cookie连接（需要先登录获取有效Cookie）');
  console.log('💡 请确保您已经通过前端登录并获得了有效的SSO_SESSION_ID Cookie');

  // 这里需要手动替换为实际的Cookie值
  const testCookie = 'SSO_SESSION_ID=your-actual-session-id-here';

  const socket2 = io('http://localhost:7002', {
    transports: ['websocket'],
    withCredentials: true,
    forceNew: true,
    autoConnect: false,
    extraHeaders: {
      'Cookie': testCookie
    }
  });

  socket2.on('connect', () => {
    console.log('✅ Socket2连接成功（带Cookie）');
    socket2.emit('joinRoom', { roomName: 'test-room-2' });
  });

  socket2.on('permission', (data) => {
    console.log('🔐 Socket2权限信息:', data);
    socket2.disconnect();
  });

  socket2.on('connect_error', (error) => {
    console.log('❌ Socket2连接错误:', error.message);
  });

  socket2.connect();

  // 等待测试2完成
  await new Promise(resolve => setTimeout(resolve, 3000));

  console.log('\n🏁 测试完成！');
  console.log('\n📋 检查要点:');
  console.log('1. Socket1应该显示为只读权限或默认权限');
  console.log('2. Socket2应该根据用户身份显示相应权限');
  console.log('3. 服务器日志应该显示Cookie解析过程');

  process.exit(0);
}

// 运行测试
testSocketAuth().catch(console.error);
